
package com.fly.socket.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * Socket建立连接（握手）和断开
 */
public class HandShake extends HttpSessionHandshakeInterceptor
{
    Logger log = LoggerFactory.getLogger(getClass());
    
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes)
        throws Exception
    {
        log.info("Websocket:用户[ID:{}]已经建立连接", ((ServletServerHttpRequest)request).getServletRequest().getSession(false).getAttribute("uid"));
        if (request instanceof ServletServerHttpRequest)
        {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            // 标记用户
            Long uid = (Long)session.getAttribute("uid");
            if (uid != null)
            {
                attributes.put("uid", uid);
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }
    
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception)
    {
        super.afterHandshake(request, response, wsHandler, exception);
        log.info("after hand");
    }
}
